<template>
  <div>
    <a-card title="酒店设施管理">
      <a-tabs v-model:activeKey="activeCategory">
        <a-tab-pane v-for="(category, index) in amenityCategories" :key="index" :tab="category.name">
          <div class="category-header">
            <div class="category-title">
              <component :is="category.icon" class="category-icon" />
              <h3>{{ category.name }}</h3>
            </div>
            <div>
              <a-button type="primary" size="small" style="margin-right: 8px;" @click="editCategory(index)">
                编辑分类
              </a-button>
              <a-popconfirm
                v-if="amenityCategories.length > 1"
                title="确定要删除这个分类吗?"
                @confirm="deleteCategory(index)"
              >
                <a-button type="primary" danger size="small" style="margin-right: 8px;">
                  删除分类
                </a-button>
              </a-popconfirm>
              <a-button type="primary" size="small" @click="addAmenity(index)">
                添加设施
              </a-button>
            </div>
          </div>
          
          <a-table :dataSource="category.items" :columns="columns" rowKey="name">
            <template #bodyCell="{ column, record, index: itemIndex }">
              <template v-if="column.key === 'available'">
                <a-switch v-model:checked="record.available" />
              </template>
              <template v-else-if="column.key === 'icon'">
                <component :is="record.icon" />
              </template>
              <template v-else-if="column.key === 'action'">
                <a-space>
                  <a-button type="primary" size="small" @click="editAmenity(activeCategory, itemIndex)">
                    编辑
                  </a-button>
                  <a-popconfirm
                    title="确定要删除这个设施吗?"
                    @confirm="removeAmenity(activeCategory, itemIndex)"
                  >
                    <a-button type="primary" danger size="small">
                      删除
                    </a-button>
                  </a-popconfirm>
                </a-space>
              </template>
            </template>
          </a-table>
        </a-tab-pane>
      </a-tabs>
    </a-card>

    <!-- 添加/编辑设施的模态框 -->
    <a-modal
      v-model:visible="modalVisible"
      :title="isEditing ? '编辑设施' : '添加设施'"
      @ok="handleModalOk"
      @cancel="modalVisible = false"
    >
      <a-form :model="currentAmenity" :label-col="{ span: 6 }" :wrapper-col="{ span: 18 }">
        <a-form-item label="设施名称">
          <a-input v-model:value="currentAmenity.name" />
        </a-form-item>
        <a-form-item label="图标">
          <a-select v-model:value="currentAmenity.iconName" style="width: 100%">
            <a-select-option v-for="icon in availableIcons" :key="icon.name" :value="icon.name">
              <div style="display: flex; align-items: center;">
                <component :is="icon.component" style="margin-right: 8px;" />
                {{ icon.name }}
              </div>
            </a-select-option>
          </a-select>
        </a-form-item>
        <a-form-item label="是否可用">
          <a-switch v-model:checked="currentAmenity.available" />
        </a-form-item>
        <a-form-item label="价格">
          <a-input-number v-model:value="currentAmenity.priceValue" style="width: 120px" :min="0" />
          <a-select v-model:value="currentAmenity.priceFormat" style="width: 120px; margin-left: 8px">
            <a-select-option value="">无价格</a-select-option>
            <a-select-option value="¥{price}">¥{价格}</a-select-option>
            <a-select-option value="¥{price}/天">¥{价格}/天</a-select-option>
            <a-select-option value="¥{price}/位">¥{价格}/位</a-select-option>
            <a-select-option value="起价{price}">起价{价格}</a-select-option>
          </a-select>
        </a-form-item>
      </a-form>
    </a-modal>

    <!-- 添加/编辑分类的模态框 -->
    <a-modal
      v-model:visible="categoryModalVisible"
      :title="isCategoryEditing ? '编辑分类' : '添加分类'"
      @ok="handleCategoryModalOk"
      @cancel="categoryModalVisible = false"
    >
      <a-form :model="currentCategory" :label-col="{ span: 6 }" :wrapper-col="{ span: 18 }">
        <a-form-item label="分类名称">
          <a-input v-model:value="currentCategory.name" />
        </a-form-item>
        <a-form-item label="图标">
          <a-select v-model:value="currentCategory.iconName" style="width: 100%">
            <a-select-option v-for="icon in availableIcons" :key="icon.name" :value="icon.name">
              <div style="display: flex; align-items: center;">
                <component :is="icon.component" style="margin-right: 8px;" />
                {{ icon.name }}
              </div>
            </a-select-option>
          </a-select>
        </a-form-item>
      </a-form>
    </a-modal>

    <div style="margin-top: 16px; display: flex; justify-content: space-between;">
      <a-button type="primary" @click="addCategory">添加设施分类</a-button>
      <a-button type="primary" @click="saveChanges">保存所有更改</a-button>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted } from 'vue';
import { message } from 'ant-design-vue';
import { useRoute } from 'vue-router';
import type { Component } from 'vue';
import { 
  apiGetHotelAmenities, 
  apiCreateHotelAmenities, 
  apiUpdateHotelAmenities 
} from '@/api/admin-api';
import { useHotelStore } from '@/stores/hotelStrore';
import { 
  CoffeeOutlined,
  WifiOutlined,
  CarOutlined,
  ExperimentOutlined,
  CustomerServiceOutlined,
  SafetyCertificateOutlined,
  GlobalOutlined,
  GiftOutlined,
  HeartOutlined,
  ThunderboltOutlined,
  ShoppingOutlined,
  TeamOutlined,
  TrophyOutlined,
  BulbOutlined,
  RestOutlined,
  SkinOutlined
} from '@ant-design/icons-vue';

// 定义类型接口
interface IconOption {
  name: string;
  component: Component;
}

interface AmenityItem {
  name: string;
  icon: Component;
  iconName: string;
  available: boolean;
  priceValue: number;
  priceFormat: string;
  price: string;
}

interface AmenityCategory {
  id?: string;
  name: string;
  icon: Component;
  iconName: string;
  items: AmenityItem[];
}

interface CurrentAmenity {
  name: string;
  iconName: string;
  available: boolean;
  priceValue: number;
  priceFormat: string;
  price?: string;
}

interface CurrentCategory {
  name: string;
  iconName: string;
}

interface AmenitiesData {
  id?: string;
  hotelId: string;
  categories: AmenityCategory[];
}

// 获取路由参数中的酒店ID
const route = useRoute();
const hotelStore = useHotelStore();

const columns = [
  { title: '图标', dataIndex: 'icon', key: 'icon' },
  { title: '设施名称', dataIndex: 'name', key: 'name' },
  { title: '价格', dataIndex: 'price', key: 'price' },
  { title: '是否可用', dataIndex: 'available', key: 'available' },
  { title: '操作', key: 'action' }
];

const availableIcons: IconOption[] = [
  { name: 'CoffeeOutlined', component: CoffeeOutlined },
  { name: 'WifiOutlined', component: WifiOutlined },
  { name: 'CarOutlined', component: CarOutlined },
  { name: 'ExperimentOutlined', component: ExperimentOutlined },
  { name: 'CustomerServiceOutlined', component: CustomerServiceOutlined },
  { name: 'SafetyCertificateOutlined', component: SafetyCertificateOutlined },
  { name: 'GlobalOutlined', component: GlobalOutlined },
  { name: 'GiftOutlined', component: GiftOutlined },
  { name: 'HeartOutlined', component: HeartOutlined },
  { name: 'ThunderboltOutlined', component: ThunderboltOutlined },
  { name: 'ShoppingOutlined', component: ShoppingOutlined },
  { name: 'TeamOutlined', component: TeamOutlined },
  { name: 'TrophyOutlined', component: TrophyOutlined },
  { name: 'BulbOutlined', component: BulbOutlined },
  { name: 'RestOutlined', component: RestOutlined },
  { name: 'SkinOutlined', component: SkinOutlined }
];

// 获取图标组件
const getIconComponent = (iconName: string): Component => {
  const icon = availableIcons.find(i => i.name === iconName);
  return icon ? icon.component : BulbOutlined;
};

// 设施分类数据
const amenityCategories = ref<AmenityCategory[]>([]);

// 当前激活的分类
const activeCategory = ref<number>(0);

// 模态框相关
const modalVisible = ref(false);
const isEditing = ref(false);
const currentAmenity = ref<CurrentAmenity>({
  name: '',
  iconName: 'BulbOutlined',
  available: true,
  priceValue: 0,
  priceFormat: '',
  price: ''
});
const editingIndex = ref(-1);

// 分类模态框相关
const categoryModalVisible = ref(false);
const isCategoryEditing = ref(false);
const currentCategory = ref<CurrentCategory>({
  name: '',
  iconName: 'BulbOutlined'
});
const editingCategoryIndex = ref(-1);

// 加载酒店设施数据
async function fetchAmenitiesData() {
  try {
    const hotelId = hotelStore.safeHotelId;
    if (!hotelId) {
      message.error('酒店ID未设置，无法加载设施信息');
      initDefaultCategories();
      return;
    }

    const response:any = await apiGetHotelAmenities(hotelId);
    if (response && response.code === 200 && response.data) {
      // 处理从后端获取的数据，转换图标名称为组件
      const data = response.data;
      if (data.categories && Array.isArray(data.categories) && data.categories.length > 0) {
        const processedCategories = data.categories.map((category: any) => {
          return {
            ...category,
            icon: getIconComponent(category.iconName),
            items: Array.isArray(category.items) ? category.items.map((item: any) => {
              return {
                ...item,
                icon: getIconComponent(item.iconName)
              };
            }) : []
          };
        });
        amenityCategories.value = processedCategories;
        message.success('设施信息加载成功');
      } else {
        // 如果没有数据，初始化默认分类
        message.info('没有找到设施数据，将使用默认设置');
        initDefaultCategories();
      }
    } else {
      message.info('没有找到设施数据，将使用默认设置');
      initDefaultCategories();
    }
  } catch (error) {
    message.error('加载酒店设施信息失败');
    console.error('加载酒店设施信息失败:', error);
    initDefaultCategories();
  }
}

// 初始化默认分类
function initDefaultCategories() {
  amenityCategories.value = [
    {
      name: '基础设施',
      icon: BulbOutlined,
      iconName: 'BulbOutlined',
      items: [
        { name: '免费WiFi', icon: WifiOutlined, iconName: 'WifiOutlined', available: true, priceValue: 0, priceFormat: '', price: '' },
        { name: '停车场', icon: CarOutlined, iconName: 'CarOutlined', available: true, priceValue: 50, priceFormat: '¥{price}/天', price: '¥50/天' },
        { name: '24小时前台', icon: CustomerServiceOutlined, iconName: 'CustomerServiceOutlined', available: true, priceValue: 0, priceFormat: '', price: '' }
      ]
    },
    {
      name: '餐饮服务',
      icon: CoffeeOutlined,
      iconName: 'CoffeeOutlined',
      items: [
        { name: '餐厅', icon: RestOutlined, iconName: 'RestOutlined', available: true, priceValue: 0, priceFormat: '', price: '' },
        { name: '自助早餐', icon: CoffeeOutlined, iconName: 'CoffeeOutlined', available: true, priceValue: 88, priceFormat: '¥{price}/位', price: '¥88/位' }
      ]
    }
  ];
}

// 组件挂载时加载数据
onMounted(async () => {
  if (!hotelStore.isInitialized) {
    await hotelStore.getHotelInfo();
  }
  
  if (hotelStore.safeHotelId) {
    fetchAmenitiesData();
  } else {
    message.warning('未找到酒店ID，无法加载设施信息');
    initDefaultCategories();
  }
});

// 添加设施
function addAmenity(categoryIndex: number) {
  isEditing.value = false;
  currentAmenity.value = {
    name: '',
    iconName: 'BulbOutlined',
    available: true,
    priceValue: 0,
    priceFormat: '',
    price: ''
  };
  activeCategory.value = categoryIndex;
  modalVisible.value = true;
}

// 编辑设施
function editAmenity(categoryIndex: number, itemIndex: number) {
  isEditing.value = true;
  const amenity = amenityCategories.value[categoryIndex].items[itemIndex];
  currentAmenity.value = {
    name: amenity.name,
    iconName: amenity.iconName,
    available: amenity.available,
    priceValue: amenity.priceValue || 0,
    priceFormat: amenity.priceFormat || '',
    price: amenity.price
  };
  editingIndex.value = itemIndex;
  modalVisible.value = true;
}

// 删除设施
function removeAmenity(categoryIndex: number, itemIndex: number) {
  amenityCategories.value[categoryIndex].items.splice(itemIndex, 1);
  message.success('设施已删除');
}

// 处理模态框确认
function handleModalOk() {
  if (!currentAmenity.value.name) {
    message.error('设施名称不能为空');
    return;
  }

  // 计算价格显示
  let priceDisplay = '';
  if (currentAmenity.value.priceFormat && currentAmenity.value.priceValue > 0) {
    priceDisplay = currentAmenity.value.priceFormat.replace('{price}', currentAmenity.value.priceValue.toString());
  }

  const newAmenity: AmenityItem = {
    name: currentAmenity.value.name,
    icon: getIconComponent(currentAmenity.value.iconName),
    iconName: currentAmenity.value.iconName,
    available: currentAmenity.value.available,
    priceValue: currentAmenity.value.priceValue,
    priceFormat: currentAmenity.value.priceFormat,
    price: priceDisplay
  };

  if (isEditing.value && editingIndex.value !== -1) {
    // 编辑现有设施
    amenityCategories.value[activeCategory.value].items[editingIndex.value] = newAmenity;
    message.success('设施已更新');
  } else {
    // 添加新设施
    amenityCategories.value[activeCategory.value].items.push(newAmenity);
    message.success('设施已添加');
  }

  modalVisible.value = false;
}

// 添加分类
function addCategory() {
  isCategoryEditing.value = false;
  currentCategory.value = {
    name: '',
    iconName: 'BulbOutlined'
  };
  categoryModalVisible.value = true;
}

// 编辑分类
function editCategory(index: number) {
  isCategoryEditing.value = true;
  const category = amenityCategories.value[index];
  currentCategory.value = {
    name: category.name,
    iconName: category.iconName
  };
  editingCategoryIndex.value = index;
  categoryModalVisible.value = true;
}

// 删除分类
function deleteCategory(index: number) {
  if (amenityCategories.value.length <= 1) {
    message.warning('至少需要保留一个分类');
    return;
  }
  
  amenityCategories.value.splice(index, 1);
  if (activeCategory.value >= amenityCategories.value.length) {
    activeCategory.value = amenityCategories.value.length - 1;
  }
  message.success('分类已删除');
}

// 处理分类模态框确认
function handleCategoryModalOk() {
  if (!currentCategory.value.name) {
    message.error('分类名称不能为空');
    return;
  }

  const newCategory: AmenityCategory = {
    name: currentCategory.value.name,
    icon: getIconComponent(currentCategory.value.iconName),
    iconName: currentCategory.value.iconName,
    items: []
  };

  if (isCategoryEditing.value && editingCategoryIndex.value !== -1) {
    // 编辑现有分类
    const oldItems = amenityCategories.value[editingCategoryIndex.value].items;
    amenityCategories.value[editingCategoryIndex.value] = { ...newCategory, items: oldItems };
    message.success('分类已更新');
  } else {
    // 添加新分类
    amenityCategories.value.push(newCategory);
    message.success('分类已添加');
    activeCategory.value = amenityCategories.value.length - 1;
  }

  categoryModalVisible.value = false;
}

// 保存所有更改
async function saveChanges() {
  try {
    const hotelId = hotelStore.safeHotelId;
    if (!hotelId) {
      message.error('酒店ID未设置，无法保存设施信息');
      return;
    }

    // 检查是否有现有记录
    let existingId = '';
    try {
      const existingData:any = await apiGetHotelAmenities(hotelId);
      if (existingData && existingData.code === 200 && existingData.data && existingData.data.id) {
        existingId = existingData.data.id;
      }
    } catch (error) {
      console.error('获取现有设施信息失败:', error);
    }

    // 准备提交的数据
    const submitData = {
      hotelId,
      id: existingId, // 如果有现有ID则保留
      categories: amenityCategories.value.map(category => ({
        name: category.name,
        iconName: category.iconName,
        items: category.items.map(item => ({
          name: item.name,
          iconName: item.iconName,
          available: item.available,
          priceValue: item.priceValue,
          priceFormat: item.priceFormat,
          price: item.price
        }))
      }))
    };

    let response:any;
    // 根据是否存在记录决定是创建还是更新
    if (existingId) {
      // 如果已存在记录，则更新
      response = await apiUpdateHotelAmenities(hotelId, submitData);
    } else {
      // 否则创建新记录
      response = await apiCreateHotelAmenities(hotelId, submitData);
    }

    if (response && response.code === 200) {
      message.success('所有设施更改已保存');
      // 重新加载数据以确保与后端同步
      fetchAmenitiesData();
    } else {
      message.error(response.msg || '保存设施信息失败');
    }
  } catch (error) {
    message.error('保存设施信息失败');
    console.error('保存设施信息失败:', error);
  }
}
</script>

<style scoped>
.category-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 16px;
}

.category-title {
  display: flex;
  align-items: center;
  gap: 8px;
}

.category-icon {
  font-size: 20px;
  color: #1890ff;
}

h3 {
  margin: 0;
  font-size: 18px;
}
</style> 